<template>
    <div class="marketing_group_detail_statistics">
        <h1>
            数据概览
            <el-tooltip effect="dark" placement="right">
                <template #content>
                    参与客户数：支付当前满减活动订单的客户数，同一客户支付多次去重。<br />
                    支付订单数：支付当前满减活动订单的总数。<br />
                    销售额：支付当前满减活动订单的实付金额总和，退款后不扣减。<br />
                    平均每笔订单金额：销售额/支付订单数。<br />
                </template>
                <el-icon><Warning /></el-icon>
            </el-tooltip>
        </h1>
        <el-row class="preview-custom-row">
            <el-col
                :span="totalCols.length > 3 ? 6 : 8"
                v-for="{ label, prop } in totalCols"
                :key="label"
                class="preview-custom-col">
                <span>{{ statisticBasic[prop] }}</span>
                <span>{{ label }}</span>
            </el-col>
        </el-row>
        <h1>参与记录</h1>
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="form" @submit.prevent>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item prop="keywords">
                            <el-input
                                v-model="form.keywords"
                                clearable
                                placeholder="订单编号/下单姓名/手机号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="16" class="zw-form-btns">
                        <div>
                            <el-button type="primary" @click="searchHandler">查询</el-button>
                            <el-button plain @click="resetHandler">清空</el-button>
                        </div>
                        <div class="export-btn">
                            共{{ totalCount || 0 }}条数据
                            <el-button plain @click="handleExport" v-auth="'enough_list:export'">导出</el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <!-- 列表 -->
        <el-table :data="tableList" type="expand" :stripe="true" class="statistics-table">
            <el-table-column
                v-for="{ prop, label, width } in tableColumns"
                :key="prop"
                :label="label"
                :prop="prop"
                :width="width || 'auto'">
                <template #default="{ row }">
                    <template v-if="prop == 'orderSn'">
                        <!-- <el-link type="primary" class="custom-el-link" @click="nameRouteHandler(row)">{{
                            row.orderSn
                        }}</el-link> -->
                        <div class="custom-el-link">
                            <span @click="nameRouteHandler(row)">{{ row.orderSn }}</span>
                        </div>
                    </template>
                    <template v-if="prop == 'buyerName'"> {{ row.buyerName }}（{{ row.buyerMobile }}） </template>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="margin-top: 15px">
            <Pagination
                :total="totalCount"
                :page-size="form.perPage"
                :current-page="form.page"
                @sizeChange="changeSizeHandler"
                @pageChange="changePageHandler" />
        </div>
    </div>
</template>

<script setup>
import { ref, unref, reactive, onMounted, computed } from 'vue';
import constants from '@/commons/constants';
import { useRouter } from 'vue-router';
import { packSelectObjUtil, exportExc, format } from '@/commons/utils';
import request from '@/request/index';
import Pagination from '@/components/Pagination.vue';

const router = useRouter();

const props = defineProps(['id', 'type', 'name']);

const form = reactive({
    page: 1, //分页页码，数字类型
    perPage: 10, //页记录数
    keywords: '' //搜索关键字
});
const formRef = ref(null);
const totalCount = ref(0);
let tableList = reactive([]);
const tableColumns = [
    { label: '订单编号', prop: 'orderSn', showOverflowTooltip: true },
    { label: '实付金额（元）', prop: 'amountTotal' },
    { label: '下单人', prop: 'buyerName', width: '200' },
    { label: '下单时间', prop: 'orderAt' }
];
let statisticBasic = reactive({});

const totalCols = computed(() => {
    const cols = [
        { label: '参与客户数', prop: 'partakeCustomerNum' },
        { label: '支付订单数', prop: 'payOrderNum' },
        { label: '销售额（元）', prop: 'totalPayAmount' },
        { label: '平均每笔订单金额（元）', prop: 'avgOrderAmount' }
    ];
    return cols;
});

/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    const { data } = await request('fullreduceRecord', { id: props.id, ...form });
    const list = (data.list || []).map(item => {
        // item.amountTotal = item.amountTotal / 100;  后端说不除100
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = data.totalCount;
};
/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
};

const nameRouteHandler = row => {
    const { href } = router.resolve({
        path: '/order/list/detail',
        query: {
            orderId: row.orderId
        }
    });
    window.open(href, '_blank');
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    queryCouponListHandler();
};

const handleExport = async () => {
    const res = await request('fullreduceExport', {
        id: props.id,
        ...form,
        perPage: unref(totalCount)
    });
    exportExc(res, props.name + '_参与记录_' + format(new Date(), 'YYYY-MM-DD_HH.mm.ss'));
};

const getStatisticBasic = async () => {
    const { data } = await request('fullreduceBasicData', { id: props.id });
    data.totalPayAmount = data.totalPayAmount / 100;
    data.avgOrderAmount = data.avgOrderAmount / 100;
    Object.assign(statisticBasic, data);
};

// const getStatisticOrderList = async () => {
//     const { data } = await request('spellGroupStatisticOrderList', { id: props.id, ...form });
//     Object.assign(statisticBasic, data);
// };

const getAllData = () => {
    // getStatisticOrderList();
    getStatisticBasic();
    searchHandler();
};

onMounted(() => {
    getAllData();
});
</script>

<style lang="scss" scoped>
$colors: #2fb6e4, #32d1ad, #ff4a1a;

.marketing_group_detail_statistics {
    .custom-status-tip {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
    }
    h1 {
        font-size: 14px;
        font-weight: 500;
        position: relative;
        padding-left: 15px;
        margin: 0;
        margin-top: 10px;
        display: flex;
        align-items: center;
        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 15%;
            width: 3px;
            height: 70%;
            background-color: var(--el-color-primary);
        }
        &:last-of-type {
            margin-bottom: 16px;
        }
        :deep(.el-icon) {
            color: #33302d;
            margin-left: 4px;
        }
    }
    .preview-custom-row {
        margin: 30px 0;
    }
    .preview-custom-col {
        display: flex;
        justify-content: center;
        align-items: flex-start;
        flex-direction: column;
        /* & + div {
            border-left: 1px solid #eee;
        } */
        span {
            font-size: 24px;
            font-family: HelveticaNeue-Medium, HelveticaNeue;
            font-weight: 500;
            color: #333333;
            margin-bottom: 7px;
            & + span {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #999999;
            }
        }
    }

    .zw-form-btns {
        display: flex;
        justify-content: space-between;
    }

    .zw-form-layout {
        background-color: #fff;
        border: 0;
        padding: 0;
    }

    .export-btn {
        color: #969696;
        font-size: 14px;
    }

    :deep {
        .statistics-table .el-table__cell {
            padding: 20px 0;
        }
        .el-table th.el-table__cell {
            padding: 12px 0;
        }
        .statistics-table .el-table__expanded-cell {
            background: #f9f9f9;
            padding: 0;
            &:hover {
                background: #f9f9f9 !important;
            }
        }
        .el-table {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #33302d;
        }
        .el-table th.el-table__cell {
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #33302d;
        }
    }
    .custom-el-link {
        color: rgb(255, 107, 0);
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        span {
            cursor: pointer;
            &:hover {
                text-decoration: underline;
            }
        }
    }
    @for $i from 1 to 4 {
        .custom-status-#{$i} {
            position: relative;
            padding-left: 14px;
            &::before {
                content: '';
                position: absolute;
                width: 8px;
                height: 8px;
                border-radius: 50%;
                left: 0px;
                top: 50%;
                transform: translateY(-50%);
                background: nth($colors, $i);
            }
        }
    }
}
</style>
